package grp.test.service.Impl;

import grp.test.common.ResponseCode;
import grp.test.common.ServerResponse;
import grp.test.dao.BookMapper;
import grp.test.dao.ReserveMapper;
import grp.test.pojo.Book;
import grp.test.pojo.Reserve;
import grp.test.pojo.ReserveKey;
import grp.test.service.IReserveService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service("iReserveService")
public class ReserveServiceImpl implements IReserveService {
    @Autowired(required = false)
    ReserveMapper reserveMapper;
    @Autowired(required = false)
    BookMapper bookMapper;

    //预定图书
    @Override
    public ServerResponse<String> addReserveBook(Integer userId, Integer bookId) {
        if(bookMapper.selectByPrimaryKey(bookId)==null)
            return ServerResponse.createByErrorCodeMessage(ResponseCode.ERROR.getCode(), "你所预定图书不存在");
        Date date = new Date();
        Reserve reserve = new Reserve(bookId,userId,date);
        int response = reserveMapper.insert(reserve);
        if(response == 0)
            return ServerResponse.createByErrorCodeMessage(ResponseCode.ERROR.getCode(), "预定预定图书失败！");
        return ServerResponse.createBySuccessMessage("预定图书成功！");
    }

    //取消预定
    @Override
    public ServerResponse<String> cancelReserveBook(Integer userId, Integer bookId) {
        int response = reserveMapper.deleteByPrimaryKey(new ReserveKey(bookId,userId));
        if (response == 0)
            return ServerResponse.createByErrorCodeMessage(ResponseCode.ERROR.getCode(),
                    "取消预定图书失败！");
        return ServerResponse.createBySuccessMessage("取消预定图书成功！");
    }

    //用户查看自己的预定图书列表
    @Override
    public ServerResponse<List<Book>> selectMyReserve(Integer userId) {
        List<Reserve> myReserveList = reserveMapper.selectByUserId(userId);
        List<Book> bookList = new ArrayList<>();
        for (int i=0;i<myReserveList.size();i++){
            bookList.add(bookMapper.selectByPrimaryKey(myReserveList.get(i).getBookId()));
        }
        return ServerResponse.createBySuccess("你的图书预定列表",bookList);
    }
}

